home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlsyn.Z / perlsyn
Encoding:
Text File  |  1998-10-28  |  29.0 KB  |  925 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlsyn - Perl syntax
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       A Perl script    consists of a sequence of declarations and
  13.       statements.  The only    things that need to be declared    in
  14.       Perl are report formats and subroutines.  See    the sections
  15.       below    for more information on    those declarations.  All
  16.       uninitialized    user-created objects are assumed to start with
  17.       a null or 0 value until they are defined by some explicit
  18.       operation such as assignment.     (Though you can get warnings
  19.       about    the use    of undefined values if you like.)  The
  20.       sequence of statements is executed just once,    unlike in sssseeeedddd
  21.       and aaaawwwwkkkk scripts, where the sequence of statements is
  22.       executed for each input line.     While this means that you
  23.       must explicitly loop over the    lines of your input file (or
  24.       files), it also means    you have much more control over    which
  25.       files    and which lines    you look at.  (Actually, I'm lying--it
  26.       is possible to do an implicit    loop with either the ----nnnn    or ----pppp
  27.       switch.  It's    just not the mandatory default like it is in
  28.       sssseeeedddd and aaaawwwwkkkk.)
  29.  
  30.       DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnnssss
  31.  
  32.       Perl is, for the most    part, a    free-form language.  (The only
  33.       exception to this is format declarations, for    obvious
  34.       reasons.) Comments are indicated by the "#" character, and
  35.       extend to the    end of the line.  If you attempt to use    /* */
  36.       C-style comments, it will be interpreted either as division
  37.       or pattern matching, depending on the    context, and C++ //
  38.       comments just    look like a null regular expression, so    don't
  39.       do that.
  40.  
  41.       A declaration    can be put anywhere a statement    can, but has
  42.       no effect on the execution of    the primary sequence of
  43.       statements--declarations all take effect at compile time.
  44.       Typically all    the declarations are put at the    beginning or
  45.       the end of the script.  However, if you're using lexically-
  46.       scoped private variables created with    my(), you'll have to
  47.       make sure your format    or subroutine definition is within the
  48.       same block scope as the my if    you expect to be able to
  49.       access those private variables.
  50.  
  51.       Declaring a subroutine allows    a subroutine name to be    used
  52.       as if    it were    a list operator    from that point    forward    in the
  53.       program.  You    can declare a subroutine without defining it
  54.       by saying sub    name, thus:
  55.  
  56.           sub myname;
  57.           $me = myname $0          or die "can't    get myname";
  58.  
  59.       Note that it functions as a list operator, not as a unary
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  71.  
  72.  
  73.  
  74.       operator; so be careful to use or instead of || in this
  75.       case.     However, if you were to declare the subroutine    as sub
  76.       myname ($), then myname would    function as a unary operator,
  77.       so either or or || would work.
  78.  
  79.       Subroutines declarations can also be loaded up with the
  80.       require statement or both loaded and imported    into your
  81.       namespace with a use statement.  See the _p_e_r_l_m_o_d manpage for
  82.       details on this.
  83.  
  84.       A statement sequence may contain declarations    of lexically-
  85.       scoped variables, but    apart from declaring a variable    name,
  86.       the declaration acts like an ordinary    statement, and is
  87.       elaborated within the    sequence of statements as if it    were
  88.       an ordinary statement.  That means it    actually has both
  89.       compile-time and run-time effects.
  90.  
  91.       SSSSiiiimmmmpppplllleeee ssssttttaaaatttteeeemmmmeeeennnnttttssss
  92.  
  93.       The only kind    of simple statement is an expression evaluated
  94.       for its side effects.     Every simple statement    must be
  95.       terminated with a semicolon, unless it is the    final
  96.       statement in a block,    in which case the semicolon is
  97.       optional.  (A    semicolon is still encouraged there if the
  98.       block    takes up more than one line, because you may
  99.       eventually add another line.)     Note that there are some
  100.       operators like eval {} and do    {} that    look like compound
  101.       statements, but aren't (they're just TERMs in    an
  102.       expression), and thus    need an    explicit termination if    used
  103.       as the last item in a    statement.
  104.  
  105.       Any simple statement may optionally be followed by a _S_I_N_G_L_E
  106.       modifier, just before    the terminating    semicolon (or block
  107.       ending).  The    possible modifiers are:
  108.  
  109.           if EXPR
  110.           unless EXPR
  111.           while EXPR
  112.           until EXPR
  113.           foreach EXPR
  114.  
  115.       The if and unless modifiers have the expected    semantics,
  116.       presuming you're a speaker of    English.  The foreach modifier
  117.       is an    iterator:  For each value in EXPR, it aliases $_ to
  118.       the value and    executes the statement.     The while and until
  119.       modifiers have the usual "while loop"    semantics (conditional
  120.       evaluated first), except when    applied    to a do-BLOCK (or to
  121.       the now-deprecated do-SUBROUTINE statement), in which    case
  122.       the block executes once before the conditional is evaluated.
  123.       This is so that you can write    loops like:
  124.  
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  137.  
  138.  
  139.  
  140.           do {
  141.           $line    = <STDIN>;
  142.           ...
  143.           }    until $line  eq    ".\n";
  144.  
  145.       See the do entry in the _p_e_r_l_f_u_n_c manpage.  Note also that
  146.       the loop control statements described    later will _N_O_T work in
  147.       this construct, because modifiers don't take loop labels.
  148.       Sorry.  You can always put another block inside of it    (for
  149.       next)    or around it (for last)    to do that sort    of thing.  For
  150.       next,    just double the    braces:
  151.  
  152.           do {{
  153.           next if $x ==    $y;
  154.           # do something here
  155.           }} until $x++ > $z;
  156.  
  157.       For last, you    have to    be more    elaborate:
  158.  
  159.           LOOP: {
  160.               do {
  161.               last if $x = $y**2;
  162.               # do something here
  163.               }    while $x++ <= $z;
  164.           }
  165.  
  166.  
  167.       CCCCoooommmmppppoooouuuunnnndddd ssssttttaaaatttteeeemmmmeeeennnnttttssss
  168.  
  169.       In Perl, a sequence of statements that defines a scope is
  170.       called a block.  Sometimes a block is    delimited by the file
  171.       containing it    (in the    case of    a required file, or the
  172.       program as a whole), and sometimes a block is    delimited by
  173.       the extent of    a string (in the case of an eval).
  174.  
  175.       But generally, a block is delimited by curly brackets, also
  176.       known    as braces.  We will call this syntactic    construct a
  177.       BLOCK.
  178.  
  179.       The following    compound statements may    be used    to control
  180.       flow:
  181.  
  182.           if (EXPR)    BLOCK
  183.           if (EXPR)    BLOCK else BLOCK
  184.           if (EXPR)    BLOCK elsif (EXPR) BLOCK ... else BLOCK
  185.           LABEL while (EXPR) BLOCK
  186.           LABEL while (EXPR) BLOCK continue    BLOCK
  187.           LABEL for    (EXPR; EXPR; EXPR) BLOCK
  188.           LABEL foreach VAR    (LIST) BLOCK
  189.           LABEL BLOCK continue BLOCK
  190.  
  191.       Note that, unlike C and Pascal, these    are defined in terms
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  203.  
  204.  
  205.  
  206.       of BLOCKs, not statements.  This means that the curly
  207.       brackets are _r_e_q_u_i_r_e_d--no dangling statements    allowed.  If
  208.       you want to write conditionals without curly brackets    there
  209.       are several other ways to do it.  The    following all do the
  210.       same thing:
  211.  
  212.           if (!open(FOO)) {    die "Can't open    $FOO: $!"; }
  213.           die "Can't open $FOO: $!"    unless open(FOO);
  214.           open(FOO)    or die "Can't open $FOO: $!";      # FOO    or bust!
  215.           open(FOO)    ? 'hi mom' : die "Can't    open $FOO: $!";
  216.                   # a bit exotic, that last one
  217.  
  218.       The if statement is straightforward.    Because    BLOCKs are
  219.       always bounded by curly brackets, there is never any
  220.       ambiguity about which    if an else goes    with.  If you use
  221.       unless in place of if, the sense of the test is reversed.
  222.  
  223.       The while statement executes the block as long as the
  224.       expression is    true (does not evaluate    to the null string
  225.       ("") or 0 or "0").  The LABEL    is optional, and if present,
  226.       consists of an identifier followed by    a colon.  The LABEL
  227.       identifies the loop for the loop control statements next,
  228.       last,    and redo.  If the LABEL    is omitted, the    loop control
  229.       statement refers to the innermost enclosing loop.  This may
  230.       include dynamically looking back your    call-stack at run time
  231.       to find the LABEL.  Such desperate behavior triggers a
  232.       warning if you use the ----wwww flag.
  233.  
  234.       If there is a    continue BLOCK,    it is always executed just
  235.       before the conditional is about to be    evaluated again, just
  236.       like the third part of a for loop in C.  Thus    it can be used
  237.       to increment a loop variable,    even when the loop has been
  238.       continued via    the next statement (which is similar to    the C
  239.       continue statement).
  240.  
  241.       LLLLoooooooopppp CCCCoooonnnnttttrrrroooollll
  242.  
  243.       The next command is like the continue    statement in C;    it
  244.       starts the next iteration of the loop:
  245.  
  246.           LINE: while (<STDIN>) {
  247.           next LINE if /^#/;      # discard comments
  248.           ...
  249.           }
  250.  
  251.       The last command is like the break statement in C (as    used
  252.       in loops); it    immediately exits the loop in question.     The
  253.       continue block, if any, is not executed:
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  269.  
  270.  
  271.  
  272.           LINE: while (<STDIN>) {
  273.           last LINE if /^$/;      # exit when done with    header
  274.           ...
  275.           }
  276.  
  277.       The redo command restarts the    loop block without evaluating
  278.       the conditional again.  The continue block, if any, is _n_o_t
  279.       executed.  This command is normally used by programs that
  280.       want to lie to themselves about what was just    input.
  281.  
  282.       For example, when processing a file like /_e_t_c/_t_e_r_m_c_a_p.  If
  283.       your input lines might end in    backslashes to indicate
  284.       continuation,    you want to skip ahead and get the next
  285.       record.
  286.  
  287.           while (<>) {
  288.           chomp;
  289.           if (s/\\$//) {
  290.               $_ .= <>;
  291.               redo unless eof();
  292.           }
  293.           # now    process    $_
  294.           }
  295.  
  296.       which    is Perl    short-hand for the more    explicitly written
  297.       version:
  298.  
  299.           LINE: while (defined($line = <ARGV>)) {
  300.           chomp($line);
  301.           if ($line =~ s/\\$//)    {
  302.               $line .= <ARGV>;
  303.               redo LINE    unless eof(); #    not eof(ARGV)!
  304.           }
  305.           # now    process    $line
  306.           }
  307.  
  308.       Note that if there were a continue block on the above    code,
  309.       it would get executed    even on    discarded lines.  This is
  310.       often    used to    reset line counters or ?pat? one-time matches.
  311.  
  312.           #    inspired by :1,$g/fred/s//WILMA/
  313.           while (<>) {
  314.           ?(fred)?    && s//WILMA $1 WILMA/;
  315.           ?(barney)?  && s//BETTY $1 BETTY/;
  316.           ?(homer)?   && s//MARGE $1 MARGE/;
  317.           }    continue {
  318.           print    "$ARGV $.: $_";
  319.           close    ARGV  if eof();          # reset $.
  320.           reset          if eof();          # reset ?pat?
  321.           }
  322.  
  323.       If the word while is replaced    by the word until, the sense
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  335.  
  336.  
  337.  
  338.       of the test is reversed, but the conditional is still    tested
  339.       before the first iteration.
  340.  
  341.       The loop control statements don't work in an if or unless,
  342.       since    they aren't loops.  You    can double the braces to make
  343.       them such, though.
  344.  
  345.           if (/pattern/) {{
  346.           next if /fred/;
  347.           next if /barney/;
  348.           # so something here
  349.           }}
  350.  
  351.       The form while/if BLOCK BLOCK, available in Perl 4, is no
  352.       longer available.   Replace any occurrence of    if BLOCK by if
  353.       (do BLOCK).
  354.  
  355.       FFFFoooorrrr LLLLooooooooppppssss
  356.  
  357.       Perl's C-style for loop works    exactly    like the corresponding
  358.       while    loop; that means that this:
  359.  
  360.           for ($i =    1; $i <    10; $i++) {
  361.           ...
  362.           }
  363.  
  364.       is the same as this:
  365.  
  366.           $i = 1;
  367.           while ($i    < 10) {
  368.           ...
  369.           }    continue {
  370.           $i++;
  371.           }
  372.  
  373.       (There is one    minor difference: The first form implies a
  374.       lexical scope    for variables declared with my in the
  375.       initialization expression.)
  376.  
  377.       Besides the normal array index looping, for can lend itself
  378.       to many other    interesting applications.  Here's one that
  379.       avoids the problem you get into if you explicitly test for
  380.       end-of-file on an interactive    file descriptor    causing    your
  381.       program to appear to hang.
  382.  
  383.           $on_a_tty    = -t STDIN && -t STDOUT;
  384.           sub prompt { print "yes? " if $on_a_tty }
  385.           for ( prompt(); <STDIN>; prompt()    ) {
  386.           # do something
  387.           }
  388.  
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  401.  
  402.  
  403.  
  404.       FFFFoooorrrreeeeaaaacccchhhh LLLLooooooooppppssss
  405.  
  406.       The foreach loop iterates over a normal list value and sets
  407.       the variable VAR to be each element of the list in turn.  If
  408.       the variable is preceded with    the keyword my,    then it    is
  409.       lexically scoped, and    is therefore visible only within the
  410.       loop.     Otherwise, the    variable is implicitly local to    the
  411.       loop and regains its former value upon exiting the loop.  If
  412.       the variable was previously declared with my,    it uses    that
  413.       variable instead of the global one, but it's still localized
  414.       to the loop.    (Note that a lexically scoped variable can
  415.       cause    problems if you    have subroutine    or format declarations
  416.       within the loop which    refer to it.)
  417.  
  418.       The foreach keyword is actually a synonym for    the for
  419.       keyword, so you can use foreach for readability or for for
  420.       brevity.  (Or    because    the Bourne shell is more familiar to
  421.       you than _c_s_h,    so writing for comes more naturally.)  If VAR
  422.       is omitted, $_ is set    to each    value.    If any element of LIST
  423.       is an    lvalue,    you can    modify it by modifying VAR inside the
  424.       loop.     That's    because    the foreach loop index variable    is an
  425.       implicit alias for each item in the list that    you're looping
  426.       over.
  427.  
  428.       If any part of LIST is an array, foreach will    get very
  429.       confused if you add or remove    elements within    the loop body,
  430.       for example with splice.   So    don't do that.
  431.  
  432.       foreach probably won't do what you expect if VAR is a    tied
  433.       or other special variable.   Don't do    that either.
  434.  
  435.       Examples:
  436.  
  437.           for (@ary) { s/foo/bar/ }
  438.  
  439.           foreach my $elem (@elements) {
  440.           $elem    *= 2;
  441.           }
  442.  
  443.           for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
  444.           print    $count,    "\n"; sleep(1);
  445.           }
  446.  
  447.           for (1..15) { print "Merry Christmas\n"; }
  448.  
  449.           foreach $item (split(/:[\\\n:]*/,    $ENV{TERMCAP}))    {
  450.           print    "Item: $item\n";
  451.           }
  452.  
  453.       Here's how a C programmer might code up a particular
  454.       algorithm in Perl:
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  467.  
  468.  
  469.  
  470.           for (my $i = 0; $i < @ary1; $i++)    {
  471.           for (my $j = 0; $j < @ary2; $j++) {
  472.               if ($ary1[$i] > $ary2[$j]) {
  473.               last;    # can't    go to outer :-(
  474.               }
  475.               $ary1[$i]    += $ary2[$j];
  476.           }
  477.           # this is where that last takes me
  478.           }
  479.  
  480.       Whereas here's how a Perl programmer more comfortable    with
  481.       the idiom might do it:
  482.  
  483.           OUTER: foreach my    $wid (@ary1) {
  484.           INNER:   foreach my $jet (@ary2) {
  485.               next OUTER if    $wid > $jet;
  486.               $wid += $jet;
  487.                }
  488.             }
  489.  
  490.       See how much easier this is?    It's cleaner, safer, and
  491.       faster.  It's    cleaner    because    it's less noisy.  It's safer
  492.       because if code gets added between the inner and outer loops
  493.       later    on, the    new code won't be accidentally executed.  The
  494.       next explicitly iterates the other loop rather than merely
  495.       terminating the inner    one.  And it's faster because Perl
  496.       executes a foreach statement more rapidly than it would the
  497.       equivalent for loop.
  498.  
  499.       BBBBaaaassssiiiicccc    BBBBLLLLOOOOCCCCKKKKssss aaaannnndddd SSSSwwwwiiiittttcccchhhh SSSSttttaaaatttteeeemmmmeeeennnnttttssss
  500.  
  501.       A BLOCK by itself (labeled or    not) is    semantically
  502.       equivalent to    a loop that executes once.  Thus you can use
  503.       any of the loop control statements in    it to leave or restart
  504.       the block.  (Note that this is _N_O_T true in eval{}, sub{}, or
  505.       contrary to popular belief do{} blocks, which    do _N_O_T count
  506.       as loops.)  The continue block is optional.
  507.  
  508.       The BLOCK construct is particularly nice for doing case
  509.       structures.
  510.  
  511.           SWITCH: {
  512.           if (/^abc/) {    $abc = 1; last SWITCH; }
  513.           if (/^def/) {    $def = 1; last SWITCH; }
  514.           if (/^xyz/) {    $xyz = 1; last SWITCH; }
  515.           $nothing = 1;
  516.           }
  517.  
  518.       There    is no official switch statement    in Perl, because there
  519.       are already several ways to write the    equivalent.  In
  520.       addition to the above, you could write
  521.  
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  533.  
  534.  
  535.  
  536.           SWITCH: {
  537.           $abc = 1, last SWITCH     if /^abc/;
  538.           $def = 1, last SWITCH     if /^def/;
  539.           $xyz = 1, last SWITCH     if /^xyz/;
  540.           $nothing = 1;
  541.           }
  542.  
  543.       (That's actually not as strange as it    looks once you realize
  544.       that you can use loop    control    "operators" within an
  545.       expression,  That's just the normal C    comma operator.)
  546.  
  547.       or
  548.  
  549.           SWITCH: {
  550.           /^abc/ && do { $abc =    1; last    SWITCH;    };
  551.           /^def/ && do { $def =    1; last    SWITCH;    };
  552.           /^xyz/ && do { $xyz =    1; last    SWITCH;    };
  553.           $nothing = 1;
  554.           }
  555.  
  556.       or formatted so it stands out    more as    a "proper" switch
  557.       statement:
  558.  
  559.           SWITCH: {
  560.           /^abc/      && do {
  561.                       $abc = 1;
  562.                       last SWITCH;
  563.                  };
  564.  
  565.           /^def/      && do {
  566.                       $def = 1;
  567.                       last SWITCH;
  568.                  };
  569.  
  570.           /^xyz/      && do {
  571.                       $xyz = 1;
  572.                       last SWITCH;
  573.                   };
  574.           $nothing = 1;
  575.           }
  576.  
  577.       or
  578.  
  579.           SWITCH: {
  580.           /^abc/ and $abc = 1, last SWITCH;
  581.           /^def/ and $def = 1, last SWITCH;
  582.           /^xyz/ and $xyz = 1, last SWITCH;
  583.           $nothing = 1;
  584.           }
  585.  
  586.       or even, horrors,
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  599.  
  600.  
  601.  
  602.           if (/^abc/)
  603.           { $abc = 1 }
  604.           elsif (/^def/)
  605.           { $def = 1 }
  606.           elsif (/^xyz/)
  607.           { $xyz = 1 }
  608.           else
  609.           { $nothing = 1 }
  610.  
  611.       A common idiom for a switch statement    is to use foreach's
  612.       aliasing to make a temporary assignment to $_    for convenient
  613.       matching:
  614.  
  615.           SWITCH: for ($where) {
  616.               /In Card Names/     && do { push @flags, '-e'; last; };
  617.               /Anywhere/          && do { push @flags, '-h'; last; };
  618.               /In Rulings/          && do {             last; };
  619.               die "unknown value for form variable where: `$where'";
  620.               }
  621.  
  622.       Another interesting approach to a switch statement is
  623.       arrange for a    do block to return the proper value:
  624.  
  625.           $amode = do {
  626.           if     ($flag    & O_RDONLY) { "r" }      # XXX: isn't this 0?
  627.           elsif     ($flag    & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
  628.           elsif     ($flag    & O_RDWR)   {
  629.               if ($flag    & O_CREAT)  { "w+" }
  630.               else            { ($flag & O_APPEND) ? "a+"    : "r+" }
  631.           }
  632.           };
  633.  
  634.       Or
  635.  
  636.           print    do {
  637.               ($flags &    O_WRONLY) ? "write-only"      :
  638.               ($flags &    O_RDWR)      ? "read-write"      :
  639.                         "read-only";
  640.           };
  641.  
  642.       Or if    you are    certainly that all the && clauses are true,
  643.       you can use something    like this, which "switches" on the
  644.       value    of the HTTP_USER_AGENT envariable.
  645.  
  646.  
  647.  
  648.  
  649.  
  650.  
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  665.  
  666.  
  667.  
  668.           #!/usr/bin/perl
  669.           #    pick out jargon    file page based    on browser
  670.           $dir = 'http://www.wins.uva.nl/~mes/jargon';
  671.           for ($ENV{HTTP_USER_AGENT}) {
  672.           $page     =    /Mac/           && 'm/Macintrash.html'
  673.                || /Win(dows    )?NT/  && 'e/evilandrude.html'
  674.                || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html'
  675.                || /Linux/           && 'l/Linux.html'
  676.                || /HP-UX/           && 'h/HP-SUX.html'
  677.                || /SunOS/           && 's/ScumOS.html'
  678.                ||              'a/AppendixB.html';
  679.           }
  680.           print "Location: $dir/$page\015\012\015\012";
  681.  
  682.       That kind of switch statement    only works when    you know the
  683.       && clauses will be true.  If you don't, the previous ?:
  684.       example should be used.
  685.  
  686.       You might also consider writing a hash instead of
  687.       synthesizing a switch    statement.
  688.  
  689.       GGGGoooottttoooo
  690.  
  691.       Although not for the faint of    heart, Perl does support a
  692.       goto statement.  A loop's LABEL is not actually a valid
  693.       target for a goto; it's just the name    of the loop.  There
  694.       are three forms: goto-LABEL, goto-EXPR, and goto-&NAME.
  695.  
  696.       The goto-LABEL form finds the    statement labeled with LABEL
  697.       and resumes execution    there.    It may not be used to go into
  698.       any construct    that requires initialization, such as a
  699.       subroutine or    a foreach loop.     It also can't be used to go
  700.       into a construct that    is optimized away.  It can be used to
  701.       go almost anywhere else within the dynamic scope, including
  702.       out of subroutines, but it's usually better to use some
  703.       other    construct such as last or die.    The author of Perl has
  704.       never    felt the need to use this form of goto (in Perl, that
  705.       is--C    is another matter).
  706.  
  707.       The goto-EXPR    form expects a label name, whose scope will be
  708.       resolved dynamically.     This allows for computed gotos    per
  709.       FORTRAN, but isn't necessarily recommended if    you're
  710.       optimizing for maintainability:
  711.  
  712.           goto ("FOO", "BAR", "GLARCH")[$i];
  713.  
  714.       The goto-&NAME form is highly    magical, and substitutes a
  715.       call to the named subroutine for the currently running
  716.       subroutine.  This is used by AUTOLOAD() subroutines that
  717.       wish to load another subroutine and then pretend that    the
  718.       other    subroutine had been called in the first    place (except
  719.       that any modifications to @_ in the current subroutine are
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  731.  
  732.  
  733.  
  734.       propagated to    the other subroutine.)    After the goto,    not
  735.       even caller()    will be    able to    tell that this routine was
  736.       called first.
  737.  
  738.       In almost all    cases like this, it's usually a    far, far
  739.       better idea to use the structured control flow mechanisms of
  740.       next,    last, or redo instead of resorting to a    goto.  For
  741.       certain applications,    the catch and throw pair of eval{} and
  742.       _d_i_e()    for exception processing can also be a prudent
  743.       approach.
  744.  
  745.       PPPPOOOODDDDssss::::    EEEEmmmmbbbbeeeeddddddddeeeedddd DDDDooooccccuuuummmmeeeennnnttttaaaattttiiiioooonnnn
  746.  
  747.       Perl has a mechanism for intermixing documentation with
  748.       source code.    While it's expecting the beginning of a    new
  749.       statement, if    the compiler encounters    a line that begins
  750.       with an equal    sign and a word, like this
  751.  
  752.           =head1 Here There    Be Pods!
  753.  
  754.       Then that text and all remaining text    up through and
  755.       including a line beginning with =cut will be ignored.     The
  756.       format of the    intervening text is described in the _p_e_r_l_p_o_d
  757.       manpage.
  758.  
  759.       This allows you to intermix your source code and your
  760.       documentation    text freely, as    in
  761.  
  762.           =item snazzle($)
  763.  
  764.           The snazzle() function will behave in the    most spectacular
  765.           form that    you can    possibly imagine, not even excepting
  766.           cybernetic pyrotechnics.
  767.  
  768.           =cut back    to the compiler, nuff of this pod stuff!
  769.  
  770.           sub snazzle($) {
  771.           my $thingie =    shift;
  772.           .........
  773.           }
  774.  
  775.       Note that pod    translators should look    at only    paragraphs
  776.       beginning with a pod directive (it makes parsing easier),
  777.       whereas the compiler actually    knows to look for pod escapes
  778.       even in the middle of    a paragraph.  This means that the
  779.       following secret stuff will be ignored by both the compiler
  780.       and the translators.
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  797.  
  798.  
  799.  
  800.           $a=3;
  801.           =secret stuff
  802.            warn "Neither POD nor CODE!?"
  803.           =cut back
  804.           print "got $a\n";
  805.  
  806.       You probably shouldn't rely upon the warn() being podded out
  807.       forever.  Not    all pod    translators are    well-behaved in    this
  808.       regard, and perhaps the compiler will    become pickier.
  809.  
  810.       One may also use pod directives to quickly comment out a
  811.       section of code.
  812.  
  813.       PPPPllllaaaaiiiinnnn    OOOOlllldddd CCCCoooommmmmmmmeeeennnnttttssss ((((NNNNooootttt!!!!))))
  814.  
  815.       Much like the    C preprocessor,    Perl can process line
  816.       directives.  Using this, one can control Perl's idea of
  817.       filenames and    line numbers in    error or warning messages
  818.       (especially for strings that are processed with eval()).
  819.       The syntax for this mechanism    is the same as for most    C
  820.       preprocessors: it matches the    regular    expression
  821.       /^#\s*line\s+(\d+)\s*(?:\s"([^"]*)")?/ with $1 being the
  822.       line number for the next line, and $2    being the optional
  823.       filename (specified within quotes).
  824.  
  825.       Here are some    examples that you should be able to type into
  826.       your command shell:
  827.  
  828.           %    perl
  829.           #    line 200 "bzzzt"
  830.           #    the `#'    on the previous    line must be the first char on line
  831.           die 'foo';
  832.           __END__
  833.           foo at bzzzt line    201.
  834.  
  835.           %    perl
  836.           #    line 200 "bzzzt"
  837.           eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
  838.           __END__
  839.           foo at - line 2001.
  840.  
  841.           %    perl
  842.           eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
  843.           __END__
  844.           foo at foo bar line 200.
  845.  
  846.           %    perl
  847.           #    line 345 "goop"
  848.           eval "\n#line " .    __LINE__ . ' "'    . __FILE__ ."\"\ndie 'foo'";
  849.           print $@;
  850.           __END__
  851.           foo at goop line 345.
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLSSSSYYYYNNNN((((1111))))
  863.  
  864.  
  865.  
  866.  
  867.  
  868.  
  869.  
  870.  
  871.  
  872.  
  873.  
  874.  
  875.  
  876.  
  877.  
  878.  
  879.  
  880.  
  881.  
  882.  
  883.  
  884.  
  885.  
  886.  
  887.  
  888.  
  889.  
  890.  
  891.  
  892.  
  893.  
  894.  
  895.  
  896.  
  897.  
  898.  
  899.  
  900.  
  901.  
  902.  
  903.  
  904.  
  905.  
  906.  
  907.  
  908.  
  909.  
  910.  
  911.  
  912.  
  913.  
  914.  
  915.  
  916.  
  917.  
  918.      Page 14                        (printed 10/23/98)
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.